﻿using ManagementApi.Models.BankTransfer;
using Newtonsoft.Json;
using PmSoft.Exceptions;
using PmSoft.Utilities;
using System.Net;

namespace ManagementApi.Services.BankTransfer;

/// <summary>
/// 银行转账服务
/// </summary>
public class BankTransferConnection
{
    private readonly IConfiguration configuration;
    private readonly ILogger logger;

    /// <summary>
    /// </summary>
    /// <param name="configuration"></param>
    /// <param name="logger"></param>
    public BankTransferConnection(IConfiguration configuration, ILogger<BankTransferConnection> logger)
    {
        this.configuration = configuration;
        this.logger = logger;
    }

    /// <summary>
    /// 请求BankTransfer服务(post)
    /// </summary>
    /// <param name="req"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    /// <exception cref="BusinessException"></exception>
    public async Task<TResult?> PostBankTransfer<TResult>(object req, string action = "")
    {
        if (req == null)
        {
            return default;
        }
        var requestData = new EncryptReq(req);
        var server = configuration.GetValue<string>($"BankTransferService") ?? throw new BusinessException("BankTransferService 参数配置不正确");
        var actionUrl = server + "/api/payroll/v1/" + action;
        HttpResult result = await HttpHelper.PostAsync(actionUrl, JsonConvert.SerializeObject(requestData));
        if (result.Code != HttpStatusCode.OK)
        {
            logger.LogError($"BankTransferService错误，URL:{actionUrl} 原因:" + result.ErrorMsg);
            throw new BusinessException($"BankTransferService错误，原因:" + result.ErrorMsg);
        }
        EncryptMess<ApiResult<TResult>>? encryptMess = JsonConvert.DeserializeObject<EncryptMess<ApiResult<TResult>>>(result?.Data.ToString() ?? "{}");
        ApiResult<TResult>? apiResult = encryptMess?.GetParame();
        if (apiResult == null || !apiResult.success)
        {
            logger.LogError($"BankTransferService错误，URL:{actionUrl}原因:" + apiResult?.msg ?? string.Empty);
            throw new BusinessException($"BankTransferService错误，原因:" + apiResult?.msg ?? string.Empty);
        }
        return apiResult.data;
    }
}